<?php

namespace app\admin\controller\dahui;

use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;


/**
 * 企业工资管理
 *
 * @icon fa fa-circle-o
 */
class Qiyegongzi extends Backend
{
    
    /**
     * Qiyegongzi模型对象
     * @var \app\admin\model\dahui\Qiyegongzi
     */
    protected $model = null;

    protected $searchFields = 'id,idnumber,ownedcompany,qiyekehu.name,qiyekehu.mobile';

    protected $noNeedRight = ['zrxy', 'index1list', 'index1', 'changetstatus', 'changetstatuspl'];


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\dahui\Qiyegongzi;
        $this->view->assign("paystatusList", $this->model->getPaystatusList());

        $this->assignconfig('audit', $this->auth->check('dahui/dingdan/audit'));
        $this->assignconfig('luru', $this->auth->check('dahui/dingdan/luru'));
        $this->assignconfig('caozuo', $this->auth->check('dahui/dingdan/caozuo'));

        $xishu = \app\admin\model\dahui\Qiyegongzixishu::get(1)->toArray();
        unset($xishu['id']);
        unset($xishu['create_time']);
        unset($xishu['update_time']);
        $xishu = array_values($xishu);
        $this->view->assign("xishu", $xishu);

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['qiyekehu'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $money = $this->model
                ->with(['qiyekehu'])
                ->where($where)
                ->order($sort, $order)
                ->sum('totalamount_z');

            $list = $this->model
                    ->with(['qiyekehu'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            $list = collection($list)->toArray();
            if ($limit == 0) {
                //导出
//                foreach ($list as &$row) {
//                    $row['idnumber'] = $this->importstr($row['idnumber']);
////                    $row['paymentnumber'] = $this->importstr($row['paymentnumber']);
//                }
            }

            $result = array("total" => $total, "rows" => $list, "extend" => ['money' => sprintf("%.2f", $money)]);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function importstr($one) {

        return "' ".$one;
    }

    //工资代缴明细表单
    public function index1()
    {

        $idnumber = $this->request->get("idnumber", '');
        $row = \app\admin\model\dahui\Qiyekehu::where('idnumber', $idnumber)->find();

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $result = $row->allowField(true)->save($params);
            $this->success('修改成功');
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    //工资代缴明细-列表
    public function index1list() {

        if ($this->request->isAjax()) {
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);

            $offset = $this->request->get("offset", 0);
            $limit = $this->request->get("limit", 0);

            $idnumber = $this->request->get("idnumber", '');
            $list = $this->model
                ->where('idnumber', $idnumber)
                ->select();

            $list = collection($list)->toArray();

            if ($limit == 0) {
//                foreach ($list as &$row) {
//                    $row['idnumber'] = $this->importstr($row['idnumber']);
////                    $row['paymentnumber'] = $this->importstr($row['paymentnumber']);
//                }
            }

            $result = array("total" => count($list), "rows" => $list);

            return json($result);
        }
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    $row = $this->model
                        ->where('payyear', $params['payyear'])
                        ->where('idnumber', $params['idnumber'])
                        ->find();

                    $params = $this->setquanxianlog($params);
                    if (!$row) {
                        $result = $this->model->allowField(true)->save($params);
                    } else {
                        $result = $row->allowField(true)->save($params);
                    }

                    $kehu = \app\admin\model\dahui\Qiyekehu::get(['idnumber' => $params['idnumber']]);
                    if (!$kehu) {
                        $kehu = new \app\admin\model\dahui\Qiyekehu;
                    }
                    $result2 = $kehu->allowField(true)->save($params);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $Gongshi = new \app\admin\model\dahui\Gongshi;
        $companyList = collection($Gongshi->field('businesstype, name, minimumcardinality, proportion')->select())->toArray();
        $this->view->assign("companyList", $companyList);

        return $this->view->fetch();
    }

    /**
     * 编辑 企业工资代缴
     */
    public function edit($ids = null)
    {
        $row = $this->model
            ->where('id', $ids)
            ->find();

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if (isset($params['paynote'])) {
                    $row->paynote = $params['paynote'];
                    $row = $this->setquanxianlog2($row);
                    $row->save();
                    $this->success();
                }

                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    $params = $this->setquanxianlog($params);
                    $result = $row->allowField(true)->save($params);

                    $kehu = \app\admin\model\dahui\Qiyekehu::get(['idnumber' => $params['idnumber']]);
                    if (!$kehu) {
                        $this->error(__('未找到企业客户！'));
                    }
                    $result2 = $kehu->allowField(true)->save($params);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $Gongshi = new \app\admin\model\dahui\Gongshi;
        $companyList = collection($Gongshi->field('businesstype, name, minimumcardinality, proportion')->select())->toArray();
        $this->view->assign("companyList", $companyList);

        $kehu = \app\admin\model\dahui\Qiyekehu::get(['idnumber' => $row['idnumber']]);
        if ($kehu) {
            $row['idnumber'] = $kehu->idnumber;
            $row['name'] = $kehu->name;
            $row['mobile'] = $kehu->mobile;
            $row['bankcardnumber'] = $kehu->bankcardnumber;
            $row['address0'] = $kehu->address0;
            $row['address1'] = $kehu->address1;
            $row['note'] = $kehu->note;
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    //http://dahui.test/admin/dahui/dingdan/zrxy?yearpayment=2019-07
    public function zrxy()
    {
        $thismoth = $this->request->get('yearpayment', '');
        if (empty($thismoth)) {
            $this->error("无效的转入年月！");
        }

        $nextmoth = date("Y-m", strtotime("+1 months", strtotime($thismoth)));

        $sql = "truncate table bb";
        Db::execute($sql);

        $sql = "insert into bb (select ownedcompany, '{$nextmoth}' as payyear, idnumber,''paynote,'未办理'paystatus,sbbase,
        gjjbase, basewages, bonuses, allowance, overtimepay, deductions, totalwages, d_pension, d_yiliao, d_shiye, d_shengyu, d_gongshang, d_chanbao,
        d_gjj, d_heji, s_pension, s_yiliao, s_shiye, s_gjj, s_heji, y_wages, tax, r_wages1, subsidies, withholding,
        r_wages2, managementfee, totalamount, year_end_award, year_end_award_tax, year_end_award_real, compensation,
        compensation_tax, compensation_real, totalamount_z from fa_dahui_qiyegongzi where payyear='{$thismoth}')";
        Db::execute($sql);

        $sql = "delete from bb where exists (select payyear from fa_dahui_qiyegongzi where fa_dahui_qiyegongzi.payyear=bb.payyear
        and fa_dahui_qiyegongzi.idnumber=bb.idnumber)";
        Db::execute($sql);

        $sql = "insert into fa_dahui_qiyegongzi (ownedcompany, payyear, idnumber,paynote,paystatus,sbbase,
        gjjbase, basewages, bonuses, allowance, overtimepay, deductions, totalwages, d_pension, d_yiliao, d_shiye, d_shengyu, d_gongshang, d_chanbao,
        d_gjj, d_heji, s_pension, s_yiliao, s_shiye, s_gjj, s_heji, y_wages, tax, r_wages1, subsidies, withholding,
        r_wages2, managementfee, totalamount, year_end_award, year_end_award_tax, year_end_award_real, compensation,
        compensation_tax, compensation_real, totalamount_z)
        select ownedcompany, payyear, idnumber,paynote,paystatus,sbbase,
        gjjbase, basewages, bonuses, allowance, overtimepay, deductions, totalwages, d_pension, d_yiliao, d_shiye, d_shengyu, d_gongshang, d_chanbao,
        d_gjj, d_heji, s_pension, s_yiliao, s_shiye, s_gjj, s_heji, y_wages, tax, r_wages1, subsidies, withholding,
        r_wages2, managementfee, totalamount, year_end_award, year_end_award_tax, year_end_award_real, compensation,
        compensation_tax, compensation_real, totalamount_z
        from bb where not exists (select idnumber from fa_dahui_qiyegongzi where idnumber=
        bb.idnumber and payyear= bb.payyear)";
        Db::execute($sql);

        $this->success("批量客户转入");
    }

    /**
     * 代缴状态++
     */
    //http://dahui.test/admin/dahui/qiyegongzi/changetstatus
    public function changetstatus($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($row->paystatus == '未办理') {
            $row->paystatus = '已办理';
        } else if ($row->paystatus == '已办理') {
            $row->paystatus = '未办理';
        }
        $row = $this->setquanxianlog2($row);

        $row->save();
        $this->success("代缴状态修改成功", null, ['paystatus' => $row->paystatus]);
    }

    public function changetstatuspl($ids = null, $type)
    {
        $list = \app\admin\model\dahui\Qiyegongzi::where('id', 'in', $ids)->select();
        foreach ($list as &$row) {
            if ($type == 0) {
                $row->paystatus = '未办理';
            } else if ($type == 1) {
                $row->paystatus = '已办理';
            }
            $row->save();
        }

        $this->success("办理状态修改成功");
    }


    public function import()
    {
        set_time_limit(0); //执行时间无限
        ini_set('memory_limit', '-1'); //内存无限

        ob_end_clean();
        ob_implicit_flush();
        header('X-Accel-Buffering: no');

        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv'])) {
            $this->error(__('Unknown data format'));
        }

        $num = 0;
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $n = 0;
            $lastline = "";
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                $oldchar = array("\t", "\"");
                $newchar = array("", "");
                $line = str_replace($oldchar, $newchar, $line);

                if ($n == 0 || preg_match('/^".*"$/', $line)) {
//操作年月,工资年月,所属公司,身份证号*,客户姓名,客户电话,银行卡号,社保基数,公积金基数,基本工资,各类奖金,各类津贴,加班工资,各类扣款,工资总额,
//单位养老,单位医疗,单位失业,单位生育,单位工伤,单位残保金,单位公积金,单位合计,个人养老,个人医疗,个人失业,个人公积金,个人合计,应发工资,专项扣除,
//个税,实发工资1,补贴,代扣,最终实发,年终奖,年终奖个税,实发年终奖,补偿金,补偿金个税,实发补偿金,总计金额,发放银行,代缴备注*,代缴状态,操作员,更新时间
                } else {
                    //内容
                    $line = $lastline.$line;
                    $filed = explode(',', $line);

                    $params = array(
                        'caozyear' => str_replace('.', '-', $filed[0]),
                        'payyear' => str_replace('.', '-', $filed[1]),
                        'ownedcompany' => $filed[2],
                        'idnumber' => $filed[3],
                        'name' => $filed[4],
                        'mobile' => $filed[5],
                        'bankcardnumber' => $filed[6],
                        'sbbase' => $filed[7],
                        'gjjbase' => $filed[8],
                        'basewages' => $filed[9],
                        'bonuses' => $filed[10],
                        'allowance' => $filed[11],

                        'overtimepay' => $filed[12],
                        'deductions' => $filed[13],
                        'totalwages' => $filed[14],
                        'd_pension' => $filed[15],
                        'd_yiliao' => $filed[16],
                        'd_shiye' => $filed[17],
                        'd_shengyu' => $filed[18],
                        'd_gongshang' => $filed[19],
                        'd_chanbao' => $filed[20],
                        'd_gjj' => $filed[21],
                        'd_heji' => $filed[22],
                        's_pension' => $filed[23],
                        's_yiliao' => $filed[24],
                        's_shiye' => $filed[25],
                        's_gjj' => $filed[26],
                        's_heji' => $filed[27],
                        'y_wages' => $filed[28],
                        'zxkc' => $filed[29],

                        'tax' => $filed[30],
                        'r_wages1' => $filed[31],
                        'subsidies' => $filed[32],
                        'withholding' => $filed[33],
                        'r_wages2' => $filed[34],
                        'year_end_award' => $filed[35],
                        'year_end_award_tax' => $filed[36],
                        'year_end_award_real' => $filed[37],
                        'compensation' => $filed[38],
                        'compensation_tax' => $filed[39],
                        'compensation_real' => $filed[40],
                        'totalamount_z' => $filed[41],

                        'ffyh' => $filed[42],
                        'paynote' => $filed[43],
                        'paystatus' => $filed[44],
                        'opman' => $filed[45],
                    );

                    $row = $this->model
                        ->where('payyear', $params['payyear'])
                        ->where('idnumber', $params['idnumber'])
                        ->find();

                    if (!$row) {
                        $result = $this->model->allowField(true)->save($params);
                    } else {
                        $result = $row->allowField(true)->save($params);
                    }

                    $kehu = \app\admin\model\dahui\Qiyekehu::get(['idnumber' => $params['idnumber']]);
                    if (!$kehu) {
                        $kehu = new \app\admin\model\dahui\Qiyekehu;
                        $result2 = $kehu->allowField(true)->save($params);
                    }

                    $num++;
                }
                $n++;
            }
            fclose($file);

        }

        $this->success("成功导入记录 ".$num);
    }

    //设置权限记录
    function setquanxianlog($params)
    {
        if (!$params) {
            return $params;
        }
        $audit = $this->auth->check('dahui/dingdan/audit');
        $luru = $this->auth->check('dahui/dingdan/luru');
        $caozuo = $this->auth->check('dahui/dingdan/caozuo');
        $admin = $audit;

        if ($audit) {
            //审核员和管理员
            $params['auditman'] = $this->auth->nickname;
        } else if ($luru) {
            $params['luruman'] = $this->auth->nickname;
        } else if ($caozuo) {
            $params['opman'] = $this->auth->nickname;
        }

        return $params;
    }

    function setquanxianlog2($row)
    {
        if (!$row) {
            return $row;
        }
        $audit = $this->auth->check('dahui/dingdan/audit');
        $luru = $this->auth->check('dahui/dingdan/luru');
        $caozuo = $this->auth->check('dahui/dingdan/caozuo');
        $admin = $audit;

        if ($audit) {
            //审核员和管理员
            $row->auditman = $this->auth->nickname;
        } else if ($luru) {
            $row->luruman = $this->auth->nickname;
        } else if ($caozuo) {
            $row->opman= $this->auth->nickname;
        }

        return $row;
    }
}
